<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="1000px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <div>
                <el-card shadow="never" body-class="!pb-[2px]" class="mb-[10px]">
                    <template #header>
                        <div class="flex justify-between items-center">
                            <div class="font-medium text-[16px]">详情</div>
                        </div>
                    </template>
                    <el-form ref="formRef1" :model="formData" label-width="80px" :rules="formRules">
                        <div class="flex flex-wrap justify-between">
                            <el-form-item class="w-[49%]" label="时间" prop="pay_time">
                                <el-date-picker
                                    class="!w-[100%]"
                                    v-model="formData.pay_time"
                                    type="datetime"
                                    value-format="X"
                                    clearable
                                    placeholder="请输入时间"
                                />
                            </el-form-item>
                            <el-form-item class="w-[49%]" label="对方名称" prop="other">
                                <el-input
                                    v-model="formData.other"
                                    placeholder="请输入对方名称"
                                    clearable
                                    :maxlength="100"
                                />
                            </el-form-item>
                            <el-form-item class="w-[100%]" label="账户" prop="account_id">
                                <el-select
                                    class="w-[100%]"
                                    v-model="formData.account_id"
                                    filterable
                                    placeholder="请选择账户"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in accountList"
                                        :key="item.id"
                                        :label="item.label"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                        </div>
                    </el-form>
                </el-card>
                <div>
                    <el-form ref="formRef" :model="formData" label-width="80px">
                        <template v-for="(item, i) in formData.list" :key="i">
                            <el-card shadow="never" body-class="!pb-[2px]" class="mb-[10px]">
                                <template #header>
                                    <div class="flex justify-between items-center">
                                        <div class="font-medium text-[16px]">拆分{{ i + 1 }}</div>
                                        <el-button
                                            @click="handleRemove(i)"
                                            type="danger"
                                            :icon="Delete"
                                            circle
                                        />
                                    </div>
                                </template>
                                <div class="flex flex-wrap justify-between">
                                    <el-form-item
                                        class="w-[49%]"
                                        label="流程编码"
                                        :prop="`list.${i}.sn`"
                                    >
                                        <el-input
                                            v-model="item.sn"
                                            placeholder="请输入流程编码"
                                            clearable
                                        />
                                    </el-form-item>
                                    <el-form-item
                                        class="w-[49%]"
                                        label="收款"
                                        :prop="`list.${i}.r_money`"
                                        :rules="disabledR(item) ? [] : formRules.r_money"
                                    >
                                        <el-input
                                            @change="handleChange(1,i)"
                                            @mousewheel.prevent
                                            :disabled="disabledR(item)"
                                            type="number"
                                            v-model="item.r_money"
                                            placeholder="请输入收款"
                                            clearable
                                            :maxlength="100"
                                        />
                                    </el-form-item>
                                    <el-form-item
                                        class="w-[49%]"
                                        label="付款"
                                        :prop="`list.${i}.p_money`"
                                        :rules="disabledP(item) ? [] : formRules.p_money"
                                    >
                                        <el-input
                                            @change="handleChange(2,i)"
                                            @mousewheel.prevent
                                            type="number"
                                            :disabled="disabledP(item)"
                                            v-model="item.p_money"
                                            placeholder="请输入付款"
                                            clearable
                                            :maxlength="100"
                                        />
                                    </el-form-item>
                                    <el-form-item
                                        class="w-[49%]"
                                        label="所属类别"
                                        :prop="`list.${i}.cate_id`"
                                        v-if="!!item.r_money || !!item.p_money"
                                        :rules="formRules.cate_id"
                                    >
                                        <el-tree-select
                                            :props="{
                                                label: 'name'
                                            }"
                                            @change="handleChange(3, i)"
                                            node-key="id"
                                            v-model="item.cate_id"
                                            :data="typeList[i]"
                                            :render-after-expand="false"
                                            placeholder="请选择所属类别"
                                        />
                                    </el-form-item>
                                    <el-form-item
                                        class="w-[49%]"
                                        label="所属部门"
                                        :prop="`list.${i}.dept_id`"
                                        v-if="item.cate_id"
                                        :rules="formRules.dept_id"
                                    >
                                        <el-tree-select
                                            :props="{
                                                label: 'name'
                                            }"
                                            node-key="id"
                                            v-model="item.dept_id"
                                            :data="deptList[i]"
                                            :render-after-expand="false"
                                            placeholder="请选择所属部门"
                                        />
                                    </el-form-item>
                                    <el-form-item
                                        class="w-[49%]"
                                        label="提交人"
                                        :prop="`list.${i}.name`"
                                    >
                                        <el-input
                                            v-model="item.name"
                                            placeholder="请输入提交人"
                                            clearable
                                        />
                                    </el-form-item>
                                    <el-form-item
                                        class="w-[49%]"
                                        label="摘要"
                                        :prop="`list.${i}.abstract`"
                                    >
                                        <el-input
                                            type="textarea"
                                            v-model="item.abstract"
                                            placeholder="请输入摘要"
                                            clearable
                                        />
                                    </el-form-item>
                                    <el-form-item
                                        class="w-[49%]"
                                        label="备注"
                                        :prop="`list.${i}.desc`"
                                    >
                                        <el-input
                                            type="textarea"
                                            v-model="item.desc"
                                            placeholder="请输入提交人"
                                            clearable
                                        />
                                    </el-form-item>
                                </div>
                            </el-card>
                        </template>
                    </el-form>
                    <div
                        @click="handleAdd"
                        class="flex items-center justify-center border-dashed rounded-[4px] cursor-pointer border-[1px] w-[100%] h-[50px] hover:border-[#666]"
                    >
                        添加
                    </div>
                </div>
            </div>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { Delete } from '@element-plus/icons-vue'
import {
    apiConfigAccountGetAll,
    apiConfigCateGetTree,
    apiConfigDeptTwoGetByCate
} from '@/api/config.ts'
import { apiRecordAdd, apiRecordDetail, apiRecordEdit } from '@/api/record.ts'
import feedback from '@/utils/feedback.ts'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const formRef1 = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑' : '新增'
})
const formData = reactive({
    id:'',
    pay_time: '',
    other: '',
    account_id: '',
    list: [
        {
            sn: '',
            cate_id: '',
            dept_id: '',
            desc: '',
            name: '',
            abstract: '',
            r_money: '',
            p_money: ''
        }
    ]
})

const disabledP = (item:any): boolean => {
    return item.r_money != '' && item.r_money != 0
}
const disabledR = (item:any): boolean => {
    return item.p_money != '' && item.p_money != 0
}

const typeList = ref<any[]>([])
const cateList = ref<any>({})
const accountList = ref<any[]>([])
const deptList = ref<any[]>([])

const formRules = {
    r_money: [
        {
            required: true,
            message: '请输入收款',
            trigger: ['blur']
        }
    ],
    p_money: [
        {
            required: true,
            message: '请输入付款',
            trigger: ['blur']
        }
    ],
    cate_id: [
        {
            required: true,
            message: '请选择所属类别',
            trigger: ['change']
        }
    ],
    pay_time: [
        {
            required: true,
            message: '请选择时间',
            trigger: ['change']
        }
    ],
    account_id: [
        {
            required: true,
            message: '请选择账户',
            trigger: ['change']
        }
    ],
    dept_id: [
        {
            required: true,
            message: '请选择所属部门',
            trigger: ['change']
        }
    ],
    // other: [
    //     {
    //         required: true,
    //         message: '请输入对方名称',
    //         trigger: ['blur']
    //     }
    // ],
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ],
    bank: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ]
}

const handleSubmit = async () => {
    await formRef1.value?.validate()
    await formRef.value?.validate()
    for (let i = 0; i < formData.list.length; i++) {
        if(formData.list[i].p_money as any == 0 && formData.list[i].r_money as any == 0){
            return feedback.msgError(`拆分${i + 1} - 收款和付款金额都为0`)
        }
    }
    mode.value == 'edit'
        ? await apiRecordEdit(formData)
        : await apiRecordAdd(formData)
    popupRef.value?.close()
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    getType()
    popupRef.value?.open()
}

const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiRecordDetail({
      id: row.id
    })
    data.list = data.list.map((item:any)=>{
        item.cate_id = item.cate_id === 0 ? '' : item.cate_id
        item.dept_id = item.dept_id === 0 ? '' : item.dept_id
        return item
    })
    setFormData(data)
    await getType()
    formData.list.forEach((item:any,i:number)=>{
        if(item.r_money != '' && item.r_money != 0){
            handleChange(1,i)
        }else if(item.p_money != '' && item.p_money != 0){
            handleChange(2,i)
        }
        handleChange(3,i)
    })
}

const handleChange = async (type:number,i?:number) => {
    if(type == 1){
        typeList.value[i!] = cateList.value['r']
    }else if(type == 2){
        typeList.value[i!] = cateList.value['p']
    }else if(type == 3){
        deptList.value[i!] = await apiConfigDeptTwoGetByCate({
            cate_id: formData.list[i!].cate_id
        })
    }
}

const handleAdd = () => {
    formData.list.push({
        sn: '',
        cate_id: '',
        dept_id: '',
        desc: '',
        name: '',
        abstract: '',
        r_money: '',
        p_money: ''
    })
}

const handleRemove = (index: number) => {
    formData.list.splice(index, 1)
}

const getType = async () => {
    cateList.value = await apiConfigCateGetTree()
    accountList.value = await apiConfigAccountGetAll()
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
